import { ref } from 'vue';
import mcApi from 'mc-c2b2m-operator-api';
import { TreeSelect } from 'ant-design-vue';
import { BasicColumn, FormSchema } from '@/components/Table';
import { PermissionModel } from 'mc-c2b2m-operator-api/types/system';

const { SystemModule } = mcApi;
const { PositionApi, DepartmentApi } = SystemModule;

const permissionList = ref<PermissionModel[]>([]);
PositionApi.getAllProductFuncPermission().then((res: PermissionModel[]) => {
  permissionList.value = res || [];
});

export const tableColumns: BasicColumn[] = [
  {
    title: '员工角色',
    dataIndex: 'name',
  },
  {
    title: '所在部门',
    dataIndex: 'orgDeptName',
  },
  {
    title: '权限',
    dataIndex: 'funcPermissionIdList',
    customRender: ({ text }) => {
      return (
        text
          ?.map?.((item: string) => {
            return permissionList.value.find((find) => find.id === item)?.name || '';
          })
          ?.join?.('、') || ''
      );
    },
  },
  {
    title: '员工数量',
    dataIndex: 'orgMemberPositionNum',
  },
];

export const tableFormSchema: FormSchema[] = [];

export const modalFormSchema: FormSchema[] = [
  {
    ifShow: false,
    field: 'id',
    label: 'id',
    component: 'Input',
  },
  {
    required: true,
    field: 'name',
    label: '角色名称',
    component: 'Input',
  },
  {
    required: true,
    field: 'orgDeptId',
    label: '所属部门',
    component: 'ApiTreeSelect',
    componentProps: ({ formActionType }) => {
      const { setFieldsValue } = formActionType;
      return {
        showSearch: true,
        valueField: 'id',
        labelField: 'name',
        treeCheckStrictly: true,
        treeDefaultExpandAll: true,
        treeNodeFilterProp: 'name',
        childrenField: 'childDeptList',
        api: DepartmentApi.getAllDepartmentOfOrg,
        showCheckedStrategy: TreeSelect.SHOW_ALL,
        onSelect: async (_, node: any) => {
          // 调整为单选操作
          const { id, name } = node;
          await setFieldsValue({ orgDeptId: id ? [{ label: name, value: id }] : [] });
        },
      };
    },
  },
];

export const permissionFormSchema: FormSchema[] = [
  {
    ifShow: false,
    field: 'id',
    label: 'id',
    component: 'Input',
  },
  {
    required: true,
    field: 'permissionIdList',
    label: '权限',
    component: 'ApiSelect',
    componentProps: {
      api: PositionApi.getAllProductFuncPermission,
      labelField: 'name',
      valueField: 'id',
      mode: 'multiple',
    },
  },
];
